package com.xcw.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.xcw.base.constant.Const;
import com.xcw.base.dto.UserDto;
import com.xcw.base.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author bhx
 * @Date 2022/8/21 22:48
 * @Description TODO
 */
@Slf4j
@Controller
public class LoginController extends BaseController{


    @RequestMapping("/login")
    public String login(){
        String code = "DY" + RandomUtil.randomNumbers(4);
        while (redisUtil.hasKey(code)){
            code = "DY" + RandomUtil.randomNumbers(4);
        }
        String ticket = RandomUtil.randomString(32);

        redisUtil.set( code, ticket,5*60);
        request.setAttribute("code", code);
        request.setAttribute("ticket", ticket);
        return "login";
    }

    @RequestMapping("/login-check")
    @ResponseBody
    public Result checkLogin(String code, String ticket){


        if(!redisUtil.hasKey("Info-" + code)) {
            return Result.fail("未登录");
        }
        String ticketBak = redisUtil.get("ticket-"  + code).toString();

        if (!ticketBak.equals(ticket)) {
            return Result.fail("登录失败");
        }

        String userJson = String.valueOf(redisUtil.get("Info-" + code));
        UserDto user = JSONUtil.toBean(userJson, UserDto.class);

        request.getSession().setAttribute(Const.CURRENT_USER, user);
        return Result.success();
    }



}
